import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useThemeConfigOut } from '@/stores/modules/themeConfig'
// element UI 语言
import eleEnLocale from 'element-plus/dist/locale/en'
import eleZhcnLocale from 'element-plus/dist/locale/zh-cn'
import eleZhtwLocale from 'element-plus/dist/locale/zh-tw'

// // 定义变量内容
const messages: any = {}
const element: any = {
  en: eleEnLocale,
  'zh-cn': eleZhcnLocale,
  'zh-tw': eleZhtwLocale
}
const itemize: any = { en: [], 'zh-cn': [], 'zh-tw': [] }
const modules: Record<string, any> = import.meta.glob('./**/*.ts', {
  eager: true
})
for (const path in modules) {
  const key = path.match(/(\S+)\/(\S+).ts/)
  if (itemize[key![2]]) itemize[key![2]].push(modules[path].default)
  else itemize[key![2]] = modules[path]
}
// 合并数组对象
function mergeArrObj(list: any, key: string) {
  let obj = {}
  list[key].forEach((i: EmptyObjectType) => {
    obj = Object.assign({}, obj, i)
  })
  return obj
}
// 处理最终格式
for (const key in itemize) {
  messages[key] = {
    name: key,
    el: element[key].el,
    message: mergeArrObj(itemize, key)
  }
}

// 读取 pinia 默认语言
const stores = useThemeConfigOut()
const { themeConfig } = storeToRefs(stores)
const i18n = createI18n({
  legacy: false,
  silentTranslationWarn: true,
  missingWarn: false,
  silentFallbackWarn: true,
  fallbackWarn: false,
  locale: themeConfig.value.globalI18n,
  fallbackLocale: eleZhcnLocale.name,
  messages
})

export function setupI18n(app: App) {
  app.use(i18n)
}

export default i18n
